﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Excel;

namespace OrderAggregator.InputFormats.NewMag
{
	/// <summary>
	/// Парсер "БАРНАУЛ, 80-Й ГВАРДЕЙСКОЙ , 40"
	/// </summary>
	public class NewMagFormat : Excel.BaseExcelFormat
	{
		const int КолонкаЗначенияВШапке = 3;

        public readonly static NewMagFormat Instance = new NewMagFormat();

        private NewMagFormat()
        {
        }

		/// <summary>
		/// Parse
		/// </summary>
		/// <param name="filePath"></param>
		/// <param name="getStream"></param>
		/// <returns></returns>
		public override BaseOrder Parse(string filePath, Func<System.IO.Stream> getStream)
		{
			if (!string.Equals(System.IO.Path.GetExtension(filePath), dotXLS, StringComparison.InvariantCultureIgnoreCase))
			{
				return null;
			}

			var dataSet = ReadAsDataset(getStream());

            if (dataSet == null || dataSet.Tables.Count == 0)
			{
				return null;
			}

			var table = dataSet.Tables[0];

			var order = new BaseOrder();

			try
			{
                order.Id = table.Rows[0][КолонкаЗначенияВШапке] as string;

                if (string.IsNullOrEmpty(order.Id))
                {
                    return null;
                }

                order.Client = table.Rows[3][КолонкаЗначенияВШапке] as string;

				order.ReceiveTime = Convert.ToDateTime(table.Rows[4][КолонкаЗначенияВШапке], RuCulture);
			}
			catch
			{
				return null;
			}

			var orderRows = GetOrderRows(table);

			foreach (var orderDataRow in orderRows)
			{
				var orderRow = new BaseOrderRow();
				orderRow.ProductCode = orderDataRow[0].ToString();
				orderRow.ProductName = orderDataRow[2].ToString();
				orderRow.UnitName = orderDataRow[4] as string;
				orderRow.Count = Convert.ToDecimal(orderDataRow[5]);

				order.OrderRows.Add(orderRow);
			}

			

			return order;
		}

		private static List<DataRow> GetOrderRows(DataTable table)
		{
			var rows = new List<DataRow>();

			int startRow = -1;

			for (int i = 5; i < table.Rows.Count; i++)
			{
				var row = table.Rows[i];

				var strColmn1 = row[0] as string;
				var strColmn2 = row[1] as string;

				if (string.Equals(strColmn1, "Код", StringComparison.InvariantCultureIgnoreCase) &&
					string.Equals(strColmn2, "Штрихкод", StringComparison.InvariantCultureIgnoreCase))
				{
					startRow = i + 1;
					break;
				}
			}

			if (startRow < 0)
			{
				return rows;
			}

			for (int i = startRow; i < table.Rows.Count; i++)
			{
				var row = table.Rows[i];

				var strColmn1 = row[0] as string;

				if (string.IsNullOrEmpty(strColmn1))
				{
					break;
				}

				rows.Add(row);
			}

			return rows;
		}
	}
}
